import React, { useState, useEffect } from 'react';
import './index.css';

interface BannerItem {
  id: string;
  image: string;
  title?: string;
  link?: string;
}

interface BannerProps {
  items: BannerItem[];
  autoPlay?: boolean;
  interval?: number;
  showDots?: boolean;
}

const Banner: React.FC<BannerProps> = ({
  items,
  autoPlay = true,
  interval = 3000,
  showDots = true
}) => {
  const [currentIndex, setCurrentIndex] = useState(0);

  useEffect(() => {
    if (!autoPlay || items.length <= 1) return;

    const timer = setInterval(() => {
      setCurrentIndex((prev) => (prev + 1) % items.length);
    }, interval);

    return () => clearInterval(timer);
  }, [autoPlay, interval, items.length]);

  const handleDotClick = (index: number) => {
    setCurrentIndex(index);
  };

  const handleBannerClick = (item: BannerItem) => {
    if (item.link) {
      console.log('Navigate to:', item.link);
    }
  };

  if (!items.length) return null;

  return (
    <div className="banner">
      <div className="banner__container">
        <div 
          className="banner__wrapper"
          style={{ transform: `translateX(-${currentIndex * 100}%)` }}
        >
          {items.map((item) => (
            <div
              key={item.id}
              className="banner__item"
              onClick={() => handleBannerClick(item)}
            >
              <img
                src={item.image}
                alt={item.title || '轮播图'}
                className="banner__image"
              />
            </div>
          ))}
        </div>
      </div>

      {showDots && items.length > 1 && (
        <div className="banner__dots">
          {items.map((_, index) => (
            <div
              key={index}
              className={`banner__dot ${index === currentIndex ? 'banner__dot--active' : ''}`}
              onClick={() => handleDotClick(index)}
            />
          ))}
        </div>
      )}
    </div>
  );
};

export default Banner; 